package top.suven.base.http.admin.tools.code;

import org.apache.commons.lang3.StringUtils;
import top.suven.base.http.admin.tools.constant.*;
import top.suven.base.http.admin.tools.vo.request.BuildCodeEditRequestVo;
import top.suven.base.http.admin.tools.vo.request.BuildCodeRequestVo;
import top.suven.base.http.admin.tools.vo.request.BuildCodeTableRequestVo;
import top.suven.base.http.admin.tools.vo.request.BuildCodeViewRequestVo;
import top.suven.base.util.utilize.DateUtil;
import top.suven.base.util.utilize.JsonUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName:
 * @Description:
 * @Author lixiangling
 * @Date 2018/7/12 19:22
 * @Copyright: (c) 2018 gc by https://www.gc.com.cn/
 * @Version : 1.0.0
 * --------------------------------------------------------
 * modifyer    modifyTime                 comment
 * <p>
 * --------------------------------------------------------
 */
public class BuildCodeUtil {
    private static Map<String, Object> dataMap = new HashMap<String, Object>();
    static String DEFINITION = "\n\t";
    static String CONTAIN = "\n\t\t";
    static String CONTAIN_NODE = "\n\t\t\t";
    static String JS = "\n\t\t\t";
    static String JS_NODE = "\n\t\t\t\t";
    static String JS_NODE_NODE = "\n\t\t\t\t\t";
    static String JS_NODE_NODE_NODE = "\n\t\t\t\t\t\t";
    static String VIEW = "\n\t\t\t\t\t\t\t";
    static String VIEW_NODE = "\n\t\t\t\t\t\t\t\t";
    static String VIEW_NODE_NODE = "\n\t\t\t\t\t\t\t\t\t";
    static String VIEW_NODE_NODE_NODE = "\n\t\t\t\t\t\t\t\t\t";
    static String EDIT = "\n\t\t\t\t";
    static String EDIT_NODE = "\n\t\t\t\t\t";
    static String EDIT_NODE_NODE = "\n\t\t\t\t\t\t";
    static String EDIT_NODE_NODE_NODE = "\n\t\t\t\t\t\t\t";
    static List<String> excludeEditColumnList = Arrays.asList(new String[]{"create_time","modify_time","status","enable_status"});
    static String BASE_PATH = "";

    public static void createCode(BuildCodeRequestVo buildCode) throws Exception{
        initMap(buildCode);
        initView(buildCode);
        initEdit(buildCode);
        dataMap.put("date", DateUtil.date("yyyy-MM-dd"));
        dataMap.put("time", DateUtil.date("HH:mm:ss"));
        BuildFreemakerUtil.projectPath = buildCode.getCodePath();

        if(buildCode.getCreateType()!=null&&buildCode.getCreateType().contains(CreateType.code.name())) {
            createCodeImpl(buildCode.getCodePath());
        }
        if(buildCode.getCreateType()!=null&&buildCode.getCreateType().contains(CreateType.listView.name())) {
            createViewImpl(buildCode.getCodePath());
        }
        if(buildCode.getCreateType()!=null&&buildCode.getCreateType().contains(CreateType.editView.name())) {
            createEditImpl(buildCode.getCodePath());
        }
        if(buildCode.getCreateType()!=null&&buildCode.getCreateType().contains(CreateType.menuSql.name())) {
            createSqlImpl(buildCode);
        }
    }

    private static void initMap(BuildCodeRequestVo buildCode) {
        dataMap.clear();
        dataMap.put("ctx", "${ctx}");
        dataMap.put("item","#{item}");
        dataMap.put("enableStatus","#{enableStatus}");
        dataMap.put("tableName", buildCode.getTableName());
        //包名
        dataMap.put("packageName", buildCode.getPackageName());
        dataMap.put("name", captureFirstUpperName(buildCode.getJavaName()));
        dataMap.put("nameLower",buildCode.getJavaName());
        dataMap.put("module", buildCode.getModule());
        dataMap.put("moduleUpper", captureFirstUpperName(buildCode.getModule()));
        dataMap.put("author",System.getProperty("user.name"));
        dataMap.put("description",buildCode.getDescription());
        dataMap.put("newdate",new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        dataMap.put("maxMenuOrder",buildCode.getMaxMenuOrder());



        StringBuffer moduleCodeList = new StringBuffer();
        StringBuffer codeRequestList = new StringBuffer();
        StringBuffer codeResponseList = new StringBuffer();
        StringBuffer codeGetSetList = new StringBuffer();
        StringBuffer results = new StringBuffer();
        List<BuildCodeTableRequestVo> tableRequestVos = buildCode.getBuildCodeTables();
        Map<String,BuildCodeViewRequestVo> viewRequestVoMap = buildCode.getBuildCodeViews().stream().collect(Collectors.toMap(BuildCodeViewRequestVo::getColumnName, e->e, (a, b)->a));
        Map<String,BuildCodeEditRequestVo> editRequestVoMap = buildCode.getBuildCodeEdits().stream().collect(Collectors.toMap(BuildCodeEditRequestVo::getColumnName, e->e, (a, b)->a));

        buildCode.getBuildCodeEdits();

        //java code
        for (BuildCodeTableRequestVo tableRequestVo : tableRequestVos){
            results.append(results.length()>0?CONTAIN_NODE:"").append("@Result(column = \"").append(tableRequestVo.getColumnName()).append("\" , property = \"").append(tableRequestVo.getPropertyName()).append("\"),");
            if(tableRequestVo.isPk()){
                dataMap.put("pkColumn", tableRequestVo.getColumnName());
                dataMap.put("pk", tableRequestVo.getPropertyName());
                dataMap.put("pkUpper", captureFirstUpperName(tableRequestVo.getPropertyName()));
                dataMap.put("pkType",captureFirstUpperName(tableRequestVo.getJavaType()));
                dataMap.put("pkCheck",String.class.getSimpleName().equals(tableRequestVo.getJavaType())?"StringUtils.isBlank(id)":"id > 0");
                dataMap.put("pkDefault",!String.class.getSimpleName().equals(tableRequestVo.getJavaType())?"(defaultValue = \"0\")":"");

                moduleCodeList.append(DEFINITION);
                if(buildCode.isAutoSeq()){
                    moduleCodeList.append("@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"").append(buildCode.getSequenceName()).append("\")");
                }else{
                    moduleCodeList.append("@GeneratedValue(strategy = GenerationType.IDENTITY)");
                }
            }else if(tableRequestVo.getColumnName().equals("status")){
                moduleCodeList.append(DEFINITION).append("@SoftDelete");
            }

            moduleCodeList.append(DEFINITION).append("@Column(name = \"").append(tableRequestVo.getColumnName()).append("\" , nullable = ")
                    .append(tableRequestVo.isNotNull()).append(")")
                    .append(DEFINITION).append("/** ").append(tableRequestVo.getColumnComment()).append(" */")
                    .append(DEFINITION).append("private ").append(propertyTransToObject(tableRequestVo.getJavaType())).append(" ")
                    .append(tableRequestVo.getPropertyName()).append(";");

            codeResponseList.append(DEFINITION).append("/** ").append(tableRequestVo.getColumnComment()).append(" */")
                    .append(DEFINITION).append("private ").append(propertyTransToObject(tableRequestVo.getJavaType())).append(" ")
                    .append(tableRequestVo.getPropertyName()).append(";");
            codeRequestList.append(DEFINITION).append("/** ").append(tableRequestVo.getColumnComment()).append(" */");
            StringBuffer verfity = new StringBuffer();
            do{
                if(!viewRequestVoMap.containsKey(tableRequestVo.getColumnName())) {
                    break;
                }
                BuildCodeViewRequestVo buildCodeViewRequestVo = viewRequestVoMap.get(tableRequestVo.getColumnName());
                if(!buildCodeViewRequestVo.isShowQuery()) {
                    break;
                }
                if(VerifyType.REGULAR.name().equals(buildCodeViewRequestVo.getVerifyType())) {
                    verfity.append(DEFINITION).append("@Pattern(regexp=\"").append(buildCodeViewRequestVo.getJavaFormRegular()).append("\",message = \"").append(buildCodeViewRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.DATE.name().equals(buildCodeViewRequestVo.getVerifyType())) {
                    verfity.append(DEFINITION).append("@DateTimeFormat(pattern = \"").append(buildCodeViewRequestVo.getJavaFormRegular()).append("\")");
                }else if(VerifyType.MAX_MIN.name().equals(buildCodeViewRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Max(value=").append(buildCodeViewRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeViewRequestVo.getJavaFormRegularMessage()).append("\")");
                    verfity.append(DEFINITION).append("@Min(value=").append(buildCodeViewRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeViewRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.MAX.name().equals(buildCodeViewRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Max(value=").append(buildCodeViewRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeViewRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.MIN.name().equals(buildCodeViewRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Min(value=").append(buildCodeViewRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeViewRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.NOTNULL.name().equals(buildCodeViewRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Size(min=").append(buildCodeViewRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeViewRequestVo.getJavaFormRegularMessage()).append("\")");
                }
            }while (false);
            do {
                if (verfity.length() != 0) {
                    break;
                }
                if(!editRequestVoMap.containsKey(tableRequestVo.getColumnName())) {
                    break;
                }
                BuildCodeEditRequestVo buildCodeEditRequestVo = editRequestVoMap.get(tableRequestVo.getColumnName());
                if(!buildCodeEditRequestVo.isShowEdit()) {
                    break;
                }
                if(VerifyType.REGULAR.name().equals(buildCodeEditRequestVo.getVerifyType())) {
                    verfity.append(DEFINITION).append("@Pattern(regexp=\"").append(buildCodeEditRequestVo.getJavaFormRegular()).append("\",message = \"").append(buildCodeEditRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.DATE.name().equals(buildCodeEditRequestVo.getVerifyType())) {
                    verfity.append(DEFINITION).append("@DateTimeFormat(pattern = \"").append(buildCodeEditRequestVo.getJavaFormRegular()).append("\")");
                }else if(VerifyType.MAX_MIN.name().equals(buildCodeEditRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Max(value=").append(buildCodeEditRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeEditRequestVo.getJavaFormRegularMessage()).append("\")");
                    verfity.append(DEFINITION).append("@Min(value=").append(buildCodeEditRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeEditRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.MAX.name().equals(buildCodeEditRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Max(value=").append(buildCodeEditRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeEditRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.MIN.name().equals(buildCodeEditRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Min(value=").append(buildCodeEditRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeEditRequestVo.getJavaFormRegularMessage()).append("\")");
                }else if(VerifyType.NOTNULL.name().equals(buildCodeEditRequestVo.getVerifyType())){
                    verfity.append(DEFINITION).append("@Size(min=").append(buildCodeEditRequestVo.getJavaFormRegular()).append(", message = \"").append(buildCodeEditRequestVo.getJavaFormRegularMessage()).append("\")");
                }
            }while (false);
            codeRequestList.append(verfity).append(DEFINITION).append("private ").append(propertyTransToObject(tableRequestVo.getJavaType())).append(" ")
                    .append(tableRequestVo.getPropertyName()).append(";");

            //set method
            codeGetSetList.append(DEFINITION)
                    .append(DEFINITION).append("public void set").append(captureFirstUpperName(tableRequestVo.getPropertyName()))
                    .append("(").append(propertyTransToObject(tableRequestVo.getJavaType())).append(" ").append(tableRequestVo.getPropertyName()).append("){")
                    .append(CONTAIN).append("this.").append(tableRequestVo.getPropertyName()).append(" = ").append(tableRequestVo.getPropertyName()).append(";")
                    .append(DEFINITION).append("}");

            //get method
            codeGetSetList.append(DEFINITION)
                    .append(DEFINITION).append("public ").append(propertyTransToObject(tableRequestVo.getJavaType())).append(" get").append(captureFirstUpperName(tableRequestVo.getPropertyName()))
                    .append("(){")
                    .append(CONTAIN).append("return this.").append(tableRequestVo.getPropertyName()).append(";")
                    .append(DEFINITION).append("}");


        }
        dataMap.put("results",results.substring(0,results.length()-1).toString());
        dataMap.put("codeRequestList", codeRequestList.toString());
        dataMap.put("codeResponseList", codeResponseList.toString());
        dataMap.put("moduleCodeList", moduleCodeList.toString());
        dataMap.put("codeGetSetList", codeGetSetList.toString());//条件
        for (String key : dataMap.keySet()) {
            System.out.println(key + "==" + dataMap.get(key));
        }

    }
    private static void initView(BuildCodeRequestVo buildCode){

        StringBuffer viewList = new StringBuffer();
        StringBuffer queryList = new StringBuffer();
        StringBuffer dateQueryInput = new StringBuffer();
        StringBuffer queryVerify = new StringBuffer();
        StringBuffer formDetail = new StringBuffer();
        StringBuffer columnBox = new StringBuffer();
        int queryFieldIndex = 0;
        List<BuildCodeTableRequestVo> tableRequestVos = buildCode.getBuildCodeTables();
        Map<String,BuildCodeViewRequestVo> viewRequestVoMap = buildCode.getBuildCodeViews().stream().collect(Collectors.toMap(BuildCodeViewRequestVo::getColumnName, e->e, (a,b)->a));
        for (BuildCodeTableRequestVo tableRequestVo : tableRequestVos) {
            String viewPk = "";
            String transValue = "";
            do {
                if (!viewRequestVoMap.containsKey(tableRequestVo.getColumnName())) {
                    break;
                }
                BuildCodeViewRequestVo viewRequestVo = viewRequestVoMap.get(tableRequestVo.getColumnName());
                if (!viewRequestVo.isShowList()) {
                    break;
                }
                formDetail.append(EDIT).append("<div class=\"layui-form-item\">")
                        .append(EDIT_NODE).append("<label class=\"layui-form-label\">").append(tableRequestVo.getColumnComment()).append("</label>")
                        .append(EDIT_NODE).append("<div class=\"layui-form-mid layui-word-aux\">${").append(dataMap.get("nameLower")).append(".").append(tableRequestVo.getPropertyName()).append("}</div>")
                        .append(EDIT).append("</div>");

                columnBox.append(CONTAIN_NODE).append(".add(\"").append(tableRequestVo.getPropertyName()).append("\", \"").append(tableRequestVo.getColumnComment()).append("\")");
                if(tableRequestVo.isPk()){
                    viewPk = ", checkbox: true";
                }else if(TableShowFlag.TRANS.name().equals(viewRequestVo.getShowFlag())&& TransType.JS.name().equals(viewRequestVo.getShowFlagTransType())){
                    transValue = ",templet: "+viewRequestVo.getShowFlagValue();
                }
                String firstView = viewList.length() == 0 ? "" : ",";
                viewPk = StringUtils.isBlank(viewPk)?",width:120":viewPk;
                viewList.append(JS_NODE).append(firstView).append("{field:'").append(tableRequestVo.getPropertyName()).append("', title: '")
                        .append(tableRequestVo.getColumnComment()).append("'").append(viewPk).append(transValue).append("}");
                if (!viewRequestVo.isShowQuery()) {
                    break;
                }
                queryFieldIndex++;
                if (queryFieldIndex % 3 == 1) {
                    queryList.append(VIEW).append("<!-- start 行信息 -->");
                    queryList.append(VIEW).append("<div class=\"layui-form-item\" style=\"margin-bottom: 0;\">");
                }

                queryFieldIndex += packQueryList(queryList,dateQueryInput,queryVerify,tableRequestVo,viewRequestVo);

                if (queryFieldIndex!=1&&queryFieldIndex % 3 == 1) {
                    queryList.append(VIEW).append("</div>");
                }
            } while (false);
        }
        do{
            if(queryFieldIndex==0){
                break;
            }
            if(queryFieldIndex % 3 == 1){
                queryList.append(VIEW).append("<!-- start 行信息 -->");
                queryList.append(VIEW).append("<div class=\"layui-form-item\" style=\"margin-bottom: 0;\">");
            }
            queryList.append(VIEW_NODE).append("<!-- start 单个元素项 -->")
                    .append(VIEW_NODE).append("<div class=\"layui-inline\">")
                    .append(VIEW_NODE_NODE).append("<button type=\"button\" class=\"layui-btn layui-btn-radius btn-min-width\" id=\"search-btn\">")
                    .append(VIEW_NODE_NODE_NODE).append("<i class=\"layui-icon layui-icon-search layuiadmin-button-btn\"></i>")
                    .append(VIEW_NODE_NODE).append("</button>")
                    .append(VIEW_NODE_NODE).append("<button type=\"reset\" class=\"layui-btn layui-btn-radius layui-btn-primary btn-min-width\">清空</button>")
                    .append(VIEW_NODE).append("</div>");
            queryList.append(VIEW).append("</div>");
        }while (false);
        dataMap.put("viewList", viewList.toString());//
        dataMap.put("queryList", queryList.toString());//
        dataMap.put("dateQueryInput", dateQueryInput.toString());
        dataMap.put("queryVerify", queryVerify.toString());
        dataMap.put("formDetail", formDetail.toString());
        dataMap.put("columnBox", columnBox.toString());
    }

    private static void initEdit(BuildCodeRequestVo buildCode){
        StringBuffer formEdit = new StringBuffer();
        StringBuffer dateFormInput = new StringBuffer();
        StringBuffer formVerify = new StringBuffer();
        List<BuildCodeTableRequestVo> tableRequestVos = buildCode.getBuildCodeTables();
        Map<String,BuildCodeEditRequestVo> editRequestVoMap = buildCode.getBuildCodeEdits().stream().collect(Collectors.toMap(BuildCodeEditRequestVo::getColumnName, e->e, (a,b)->a));

        formEdit.append(EDIT).append("<input type=\"hidden\" id=\"").append(dataMap.get("pk")).append("\" name=\"").append(dataMap.get("pk")).append("\" value=\"${").append(dataMap.get("nameLower")).append(".").append(dataMap.get("pk")).append("}\">");

        for (BuildCodeTableRequestVo tableRequestVo : tableRequestVos) {
            do {
                if (!editRequestVoMap.containsKey(tableRequestVo.getColumnName())) {
                    break;
                }

                if(excludeEditColumnList.contains(tableRequestVo.getColumnName())){
                    break;
                }
                BuildCodeEditRequestVo editRequestVo = editRequestVoMap.get(tableRequestVo.getColumnName());
                if(tableRequestVo.getPropertyName().equals(dataMap.get("pk"))){
                    break;
                }else if(!editRequestVo.isShowEdit()){
                    formEdit.append(EDIT).append("<input type=\"hidden\" id=\"").append(tableRequestVo.getPropertyName()).append("\" name=\"").append(tableRequestVo.getPropertyName()).append("\" value=\"${").append(dataMap.get("nameLower")).append(".").append(tableRequestVo.getPropertyName()).append("}\">");
                    break;
                }
                //多选项值（非TEXT处理）
                List<BuildViewSelectBean> viewSelectBeanList = new ArrayList<>();
                if(StringUtils.isNotBlank(editRequestVo.getEditType())){
                    viewSelectBeanList.addAll(JsonUtils.readValue(editRequestVo.getEditFlagValue(),List.class));
                }
                //日期输入框
                if(tableRequestVo.getJavaType().equals(Date.class.getSimpleName())){
                    dateFormInput.append(CONTAIN).append("laydate.render({")
                            .append(JS).append("elem: '#").append(tableRequestVo.getPropertyName()).append("'")
                            .append(CONTAIN).append("});");
                }
                if(FormShowFlag.TEXT.name().equals(editRequestVo.getEditFlag())) {
                    formVerify.append(formVerify.length() > 0 ? JS + "," : JS).append(tableRequestVo.getPropertyName()).append(": function(value, item){");
                    if(VerifyType.REGULAR.name().equals(editRequestVo.getVerifyType())) {
                        formVerify.append(JS_NODE).append("if(").append(editRequestVo.getJsFormRegular()).append(".test(value)){");
                    }else if(VerifyType.DATE.name().equals(editRequestVo.getVerifyType())) {
                        formVerify.append(JS_NODE).append("if(").append(editRequestVo.getJsFormRegular()).append("(value)){");
                    }else if(VerifyType.MAX_MIN.name().equals(editRequestVo.getVerifyType())){
                        String[] maxMin = editRequestVo.getJsFormRegular().split("|");
                        formVerify.append(JS_NODE).append("if(value < ").append(maxMin[0]).append(" || value > ").append(maxMin[1]).append("){");
                    }else if(VerifyType.MAX.name().equals(editRequestVo.getVerifyType())){
                        formVerify.append(JS_NODE).append("if(value > ").append(editRequestVo.getJsFormRegular()).append("){");
                    }else if(VerifyType.MIN.name().equals(editRequestVo.getVerifyType())){
                        formVerify.append(JS_NODE).append("if(value < ").append(editRequestVo.getJsFormRegular()).append("){");
                    }else if(VerifyType.NOTNULL.name().equals(editRequestVo.getVerifyType())){
                        formVerify.append(JS_NODE).append("if(!value){");
                    }
                    formVerify.append(JS_NODE_NODE).append("return '").append(editRequestVo.getJsFormRegularMessage()).append("'")
                            .append(JS_NODE).append("}").append(JS).append("}");
                }
                //form元素
                formEdit.append(EDIT).append("<div class=\"layui-form-item\">");
                formEdit.append(EDIT_NODE).append("<label class=\"layui-form-label\">").append(tableRequestVo.getColumnComment()).append("</label>");
                formEdit.append(EDIT_NODE).append("<div class=\"layui-input-block\">");
                if(FormShowFlag.TEXT.name().equals(editRequestVo.getEditFlag())) {
                    formEdit.append(EDIT_NODE_NODE).append("<input type=\"text\" id=\"").append(tableRequestVo.getPropertyName()).append("\" name=\"").append(tableRequestVo.getPropertyName()).append("\" lay-verify=\"").append(tableRequestVo.getPropertyName()).append("\" value=\"${").append(dataMap.get("nameLower")).append(".").append(tableRequestVo.getPropertyName()).append("}\" autocomplete=\"off\" placeholder=\"请输入").append(tableRequestVo.getColumnComment()).append("\" class=\"layui-input\" >");
                }else if(FormShowFlag.SELECT.name().equals(editRequestVo.getEditFlag())){
                    formEdit.append(EDIT_NODE_NODE).append("<select name=\"").append(tableRequestVo.getPropertyName()).append("\" >");
                    for(BuildViewSelectBean viewSelectBean : viewSelectBeanList) {
                        formEdit.append(EDIT_NODE_NODE_NODE).append("\t<option value=\"").append(viewSelectBean.getValue()).append("\">").append(viewSelectBean.getText()).append("</option>");
                    }
                    formEdit.append(EDIT_NODE_NODE).append("</select>");
                }else if(FormShowFlag.CHECKBOX.name().equals(editRequestVo.getEditFlag())){
                    for(BuildViewSelectBean viewSelectBean : viewSelectBeanList) {
                        formEdit.append(EDIT_NODE_NODE).append(" <input type=\"checkbox\" name=\"").append(tableRequestVo.getPropertyName()).append("\" lay-skin=\"primary\" value=\"")
                                .append(viewSelectBean.getValue()).append("\" title=\"").append(viewSelectBean.getText()).append("\">");
                    }
                }else if(FormShowFlag.RODIO.name().equals(editRequestVo.getEditFlag())){
                    for(BuildViewSelectBean viewSelectBean : viewSelectBeanList) {
                        formEdit.append(EDIT_NODE_NODE).append(" <input type=\"radio\" name=\"").append(tableRequestVo.getPropertyName()).append("\" lay-skin=\"primary\" value=\"")
                                .append(viewSelectBean.getValue()).append("\" title=\"").append(viewSelectBean.getText()).append("\">");
                    }
                }
                formEdit.append(EDIT_NODE).append("</div>");
                formEdit.append(EDIT).append("</div>");

            } while (false);
        }
        dataMap.put("formEdit", formEdit.toString());//
        dataMap.put("dateFormInput", dateFormInput.toString());
        dataMap.put("formVerify", formVerify.toString());
    }

    private static int packQueryList(StringBuffer queryList,StringBuffer dateQueryInput, StringBuffer queryVerify,BuildCodeTableRequestVo tableRequestVo,BuildCodeViewRequestVo viewRequestVo){

        int divCount = 0;
        queryList.append(VIEW_NODE).append("<!-- start 单个元素项 -->");
        queryList.append(VIEW_NODE).append("<div class=\"layui-inline\">");
        queryList.append(VIEW_NODE_NODE).append("<label class=\"layui-form-label\">").append(tableRequestVo.getColumnComment()).append("</label>");
        queryList.append(VIEW_NODE_NODE).append("<div class=\"layui-input-inline\">");

        String maxLength = tableRequestVo.getLength()==null?"":"maxlength=\""+tableRequestVo.getLength()+"\"";
        List<BuildViewSelectBean> viewSelectBeanList = new ArrayList<>();
        if(StringUtils.isNotBlank(viewRequestVo.getQueryFlagValue())){
            viewSelectBeanList.addAll(JsonUtils.string2List(viewRequestVo.getQueryFlagValue(),BuildViewSelectBean.class));
        }

        if(FormShowFlag.TEXT.name().equals(viewRequestVo.getQueryFlag())){
            queryVerify.append(queryVerify.length() > 0 ? JS + "," : JS).append(tableRequestVo.getPropertyName()).append(": function(value, item){");
            if (VerifyType.REGULAR.name().equals(viewRequestVo.getVerifyType())) {
                queryVerify.append(JS_NODE).append("if(").append(viewRequestVo.getJsFormRegular()).append(".test(value)){");
            } else if (VerifyType.DATE.name().equals(viewRequestVo.getVerifyType())) {
                queryVerify.append(JS_NODE).append("if(").append(viewRequestVo.getJsFormRegular()).append("(value)){");
            } else if (VerifyType.MAX_MIN.name().equals(viewRequestVo.getVerifyType())) {
                String[] maxMin = viewRequestVo.getJsFormRegular().split("|");
                queryVerify.append(JS_NODE).append("if(value < ").append(maxMin[0]).append(" || value > ").append(maxMin[1]).append("){");
            } else if (VerifyType.MAX.name().equals(viewRequestVo.getVerifyType())) {
                queryVerify.append(JS_NODE).append("if(value > ").append(viewRequestVo.getJsFormRegular()).append("){");
            } else if (VerifyType.MIN.name().equals(viewRequestVo.getVerifyType())) {
                queryVerify.append(JS_NODE).append("if(value < ").append(viewRequestVo.getJsFormRegular()).append("){");
            } else if (VerifyType.NOTNULL.name().equals(viewRequestVo.getVerifyType())) {
                queryVerify.append(JS_NODE).append("if(!value){");
            } else if (VerifyType.NOTNULL.name().equals(viewRequestVo.getVerifyType())) {
                queryVerify.append(JS_NODE).append("if(!value){");
            }
            queryVerify.append(JS_NODE_NODE).append("return '").append(viewRequestVo.getJsFormRegularMessage()).append("'").append(JS_NODE).append("}").append(JS).append("}");;


            if(tableRequestVo.getJavaType().equals(Date.class.getSimpleName())){
                queryList.append(VIEW_NODE_NODE_NODE).append("<input type=\"text\" id=\"").append(tableRequestVo.getPropertyName()).append("Start\" name=\"")
                        .append(tableRequestVo.getPropertyName()).append("Start\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"请选择日期")
                        .append("\" ").append(maxLength).append(" class=\"layui-input\">");
                queryList.append(VIEW_NODE_NODE).append("</div>");
                queryList.append(VIEW_NODE_NODE).append("<label class=\"layui-form-label\">至</label>");
                queryList.append(VIEW_NODE_NODE).append("<div class=\"layui-input-inline\">");
                queryList.append(VIEW_NODE_NODE_NODE).append("<input type=\"text\" id=\"").append(tableRequestVo.getPropertyName()).append("End\" name=\"")
                        .append(tableRequestVo.getPropertyName()).append("End\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"请选择日期")
                        .append("\" ").append(maxLength).append(" class=\"layui-input\">");
                dateQueryInput.append(JS)
                        .append(JS).append("laydate.render({")
                        .append(JS_NODE).append("elem: '#").append(tableRequestVo.getPropertyName()).append("Start'")
                        .append(JS).append("});")
                        .append(JS).append("")
                        .append(JS).append("laydate.render({")
                        .append(JS_NODE).append("elem: '#").append(tableRequestVo.getPropertyName()).append("End'")
                        .append(JS).append("});");
                divCount++;
            }else{
                queryList.append(VIEW_NODE_NODE_NODE).append("<input type=\"text\"  id=\"").append(tableRequestVo.getPropertyName()).append("\" name=\"")
                        .append(tableRequestVo.getPropertyName()).append("\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"请输入")
                        .append(tableRequestVo.getColumnComment()).append("\" ").append(maxLength).append(" class=\"layui-input\">");
                if(tableRequestVo.getPropertyName().endsWith("Date")||tableRequestVo.getPropertyName().endsWith("Time")){
                    dateQueryInput.append(JS)
                            .append(JS).append("laydate.render({")
                            .append(JS_NODE).append("elem: '#").append(tableRequestVo.getPropertyName()).append("'")
                            .append(JS).append("});");
                }
            }
        }else if(FormShowFlag.SELECT.name().equals(viewRequestVo.getQueryFlag())){

            queryList.append(VIEW_NODE_NODE_NODE).append("<select name=\"").append(tableRequestVo.getPropertyName()).append("\" >");
            for(BuildViewSelectBean viewSelectBean : viewSelectBeanList) {
                queryList.append(VIEW_NODE_NODE_NODE).append("\t<option value=\"").append(viewSelectBean.getValue()).append("\">").append(viewSelectBean.getText()).append("</option>");
            }
            queryList.append(VIEW_NODE_NODE_NODE).append("</select>");
        }else if(FormShowFlag.CHECKBOX.name().equals(viewRequestVo.getQueryFlag())){
            for(BuildViewSelectBean viewSelectBean : viewSelectBeanList) {
                queryList.append(VIEW_NODE_NODE_NODE).append(" <input type=\"checkbox\" name=\"").append(tableRequestVo.getPropertyName()).append("\" lay-skin=\"primary\" value=\"")
                        .append(viewSelectBean.getValue()).append("\" title=\"").append(viewSelectBean.getText()).append("\">");
            }
        }else if(FormShowFlag.RODIO.name().equals(viewRequestVo.getQueryFlag())){
            for(BuildViewSelectBean viewSelectBean : viewSelectBeanList) {
                queryList.append(VIEW_NODE_NODE_NODE).append(" <input type=\"radio\" name=\"").append(tableRequestVo.getPropertyName()).append("\" lay-skin=\"primary\" value=\"")
                        .append(viewSelectBean.getValue()).append("\" title=\"").append(viewSelectBean.getText()).append("\">");
            }
        }

        queryList.append(VIEW_NODE_NODE).append("</div>");
        queryList.append(VIEW_NODE).append("</div>");
        queryList.append(VIEW_NODE).append("<!-- end 单个元素项 -->");
        return divCount;
    }



    private static String propertyTransToObject(String propertyName) {
        if("int".equals(propertyName)){
            return "Integer";
        }
        return captureFirstUpperName(propertyName);

    }

    private static String captureFirstUpperName(String name) {
        char[] cs=name.toCharArray();
        if(cs[0]<97 || cs[0]>122){
            return name;
        }
        cs[0]-=32;
        return String.valueOf(cs);

    }

    private static String captureFirstLowerName(String name) {
        char[] cs=name.toCharArray();
        if(cs[0]<65 || cs[0]>90){
            return name;
        }
        cs[0]+=32;
        return String.valueOf(cs);
    }

    private static void createCodeImpl(String codePath) throws Exception{
        String targetPath = codePath + BuildFreemakerUtil.tempProjectPath;
        String outModuleFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/model/" + dataMap.get("name") + ".java";

        String outVoRequestFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/vo/request/" + dataMap.get("name") + "RequestVo.java";

        String outVoResponseFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/vo/response/" + dataMap.get("name") + "ResponseVo.java";

        String outVoValidFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/vo/valid/" + dataMap.get("moduleUpper") + "ValidGroup.java";

        String outDaoFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/dao/" + dataMap.get("name") + "WebDao.java";

        String outServiceFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/service/"  + dataMap.get("name") + "WebService.java";

        String outServiceImplFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/service/impl/"  + dataMap.get("name") + "WebServiceImpl.java";

        String outControlFileName = targetPath
                + (dataMap.get("packageName") + "").replaceAll("\\.", "/")
                + "/controller/"  + dataMap.get("name") + "WebController.java";


        BuildFreemakerUtil.writeTemp(dataMap, "code_model.jsp", outModuleFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_vo_request.jsp", outVoRequestFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_vo_response.jsp", outVoResponseFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_dao.jsp", outDaoFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_service.jsp", outServiceFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_service_impl.jsp", outServiceImplFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_controller.jsp", outControlFileName);

        File validFile = new File(outVoValidFileName);
        if(!validFile.exists()){
            BuildFreemakerUtil.writeTemp(dataMap, "code_valid.jsp", outVoValidFileName);
        }
    }

    private static void createViewImpl(String codePath) throws Exception{
        String htmlPath = codePath + BuildFreemakerUtil.htmlPath;
        String outViewFileName = htmlPath
                + "/"+dataMap.get("module")+"/"+dataMap.get("nameLower")+ "_index.jsp";
        String outDetailFileName = htmlPath
                + "/"+dataMap.get("module")+"/"+dataMap.get("nameLower") + "_detail.jsp";

        BuildFreemakerUtil.writeTemp(dataMap, "code_list_jsp.jsp", outViewFileName);
        BuildFreemakerUtil.writeTemp(dataMap, "code_detail_jsp.jsp", outDetailFileName);
    }

    private static void createEditImpl(String codePath) throws Exception{
        String htmlPath = codePath + BuildFreemakerUtil.htmlPath;
        String outEditFileName = htmlPath
                + "/"+dataMap.get("module")+"/"+dataMap.get("nameLower")+ "_edit.jsp";
        BuildFreemakerUtil.writeTemp(dataMap, "code_edit_jsp.jsp", outEditFileName);
    }

    private static void createSqlImpl(BuildCodeRequestVo buildCode) throws Exception{
        String sqlPath = buildCode.getSqlPath();
        String outEditFileName = sqlPath
                + "/"+dataMap.get("nameLower")+ ".sql";
        BuildFreemakerUtil.writeTemp(dataMap, "code_sql.jsp", outEditFileName);
    }
}
